/*
 * Copyright 2014 Cungmua, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cungmua.vn.kiosk.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.R.integer;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import cungmua.vn.kiosk.AbstractActivity;
import cungmua.vn.kiosk.R;
import cungmua.vn.kiosk.adapter.ReportAdapter;
import cungmua.vn.kiosk.db.DatabaseHandler;
import cungmua.vn.kiosk.handle.ServiceHandler;
import cungmua.vn.kiosk.handle.SkuSynchonizeHandler;
import cungmua.vn.kiosk.model.DonHang;
import cungmua.vn.kiosk.model.SKU;
import cungmua.vn.kiosk.model.SkuSynchonize;
import cungmua.vn.kiosk.network.CallServices;
import cungmua.vn.kiosk.utils.Constant;
import cungmua.vn.kiosk.utils.Utils;
import cungmua.vn.kiosk.utils.WriteLog;

/**
 * @author kelvin.nguyen
 * 
 */
public class ThongKeActivity extends AbstractActivity {
	private DatabaseHandler db;
	private LinearLayout root_view;
	private Button btn_all;
	private Button btn_product;
	private Button btn_voucher;
	private ProgressDialog dialog;
	private LinearLayout layout_all;
	private LayoutInflater inflater;

	private ListView list_all_donhangs;
	private List<SKU> skus = new ArrayList<SKU>();
	private List<SkuSynchonize> skuSynchonizes = new ArrayList<SkuSynchonize>();
	private double total = 0;
	private TextView txt_total;

	private ReportAdapter mAdapter;
	private Button btn_synchonize;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_thongke);
		initView();
		db = new DatabaseHandler(getParent());

		for (SKU sku : db.getReportSkus(SKU_TYPE_ALL)) {
			total += sku.getPrice() * sku.getSku_Quantity_Delivery();
		}
		txt_total.setText(Utils.priceWithoutDecimal(total)
				+ Constant.PREFIX_CURRENCY);

		if (db.getAllDonHangDangGiao().size() > 0) {
			findViewById(R.id.btn_xac_nhan).setVisibility(GONE);
		}
		checkStatusSynchonize();

		new getDonHangCompleted(SKU_TYPE_ALL).execute();
	}

	public void initView() {
		txt_total = (TextView) findViewById(R.id.txt_total);
		btn_synchonize = (Button) findViewById(R.id.btn_synchonize);
		root_view = (LinearLayout) findViewById(R.id.root_view);
		btn_all = (Button) findViewById(R.id.btn_all);
		btn_product = (Button) findViewById(R.id.btn_product);
		btn_voucher = (Button) findViewById(R.id.btn_voucher);

		btn_all.setOnClickListener(onclick);
		btn_product.setOnClickListener(onclick);
		btn_voucher.setOnClickListener(onclick);
		btn_synchonize.setOnClickListener(onclick);

		inflater = LayoutInflater.from(getParent());

		// lookup layout for all form
		layout_all = (LinearLayout) inflater.inflate(
				R.layout.layout_thongke_all, null);

		list_all_donhangs = (ListView) layout_all
				.findViewById(R.id.list_all_donhangs);

	}

	public OnClickListener onclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_all:
				// change color text tabs
				setColorTabs(SKU_TYPE_ALL);

				btn_all.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1));

				btn_product.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				btn_voucher.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				root_view.removeAllViews();
				root_view.addView(layout_all);
				new getDonHangCompleted(SKU_TYPE_ALL).execute();
				break;

			case R.id.btn_product:

				// change color text tabs
				setColorTabs(SKU_TYPE_PRODUCT);

				btn_all.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				btn_product.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1));

				btn_voucher.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				root_view.removeAllViews();
				root_view.addView(layout_all);

				new getDonHangCompleted(SKU_TYPE_PRODUCT).execute();

				break;
			case R.id.btn_voucher:

				// change color text tabs
				setColorTabs(SKU_TYPE_VOUCHER);

				btn_all.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				btn_product.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1_selected));

				btn_voucher.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.tab_menu1));

				root_view.removeAllViews();
				root_view.addView(layout_all);

				new getDonHangCompleted(SKU_TYPE_VOUCHER).execute();

				break;
			case R.id.btn_synchonize:
				new synchonizeDonHang(db.getAllDonHangsSynchonizes()).execute();
				break;
			case R.id.btn_xac_nhan:
				
				break;

			default:
				break;
			}

		}
	};

	public class getDonHangCompleted extends AsyncTask<Void, Void, Void> {
		int mode = 0;

		public getDonHangCompleted(int mode) {
			this.mode = mode;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// dialog = new ProgressDialog(getParent());
			// dialog.setMessage(getResources().getString(R.string.label_dialog));
			// dialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			skus = db.getReportSkus(mode);

			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// if (dialog.isShowing()) {
			// dialog.dismiss();
			// }
			if (skus.size() > 0) {
				mAdapter = new ReportAdapter(self, skus);
				list_all_donhangs.setAdapter(mAdapter);
			} else {
				root_view.removeAllViews();
			}
		}

	}
	
	public class FinishedDonHang extends AsyncTask<Void, Void, Integer>{

		@Override
		protected Integer doInBackground(Void... params) {
			try {
				String json = CallServices.finishedDonHang(self,String.valueOf( db.getAllNhanviens().get(0).getId()));

				if (json != null) {
					json = "{\"backup\":" + json + "}";
					JSONObject obj = new JSONObject(json);
					JSONObject arr = obj.getJSONObject("backup");
					int counter = Integer.parseInt(arr.getString("Code"));
					return counter;
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
			// WriteLog.d(TAG, json);
			// backup faild
			return 1;
		}
		
	}

	public class synchonizeDonHang extends AsyncTask<Void, Void, Integer> {

		private List<DonHang> donhangs;

		public synchonizeDonHang(List<DonHang> donhangs) {
			this.donhangs = donhangs;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(getParent());
			dialog.setMessage(getResources().getString(R.string.label_dialog));
			dialog.show();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			try {
				String json = CallServices.SyncOrder(self,
						db.getAllDonHangsSynchonizes());

				if (json != null) {
					WriteLog.d(TAG, json);
					ServiceHandler service = new ServiceHandler();
					SkuSynchonizeHandler skuSynchonize = service
							.getSkuSynchonizes(json);
					skuSynchonizes = skuSynchonize.getData();
				}

			} catch (Exception e) {

			}
			// WriteLog.d(TAG, json);
			// backup faild
			return 1;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (skuSynchonizes.size() > 0) {
				for (SkuSynchonize skuSyn : skuSynchonizes) {
					if (skuSyn.getStatus() == 0) {
						db.updateSynchonizeDonhang(skuSyn.getOrderId(), 0);
					}
				}
			}
			
			checkStatusSynchonize();
			
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
		}

	}

	public void checkStatusSynchonize(){
		if (db.getAllDonHangsSynchonizes().size() > 0) {
			findViewById(R.id.btn_xac_nhan).setVisibility(GONE);
			btn_synchonize.setText(db.getAllDonHangsSynchonizes().size()
					+ getResources().getString(R.string.label_synchonize));
		} else {
			findViewById(R.id.btn_synchonize).setVisibility(GONE);
		}
	}
	public void setColorTabs(int position) {
		switch (position) {
		case 0:
			btn_all.setTextColor(getResources().getColor(R.color.black));
			btn_product.setTextColor(getResources().getColor(R.color.white));
			btn_voucher.setTextColor(getResources().getColor(R.color.white));
			break;
		case 1:
			btn_all.setTextColor(getResources().getColor(R.color.white));
			btn_product.setTextColor(getResources().getColor(R.color.black));
			btn_voucher.setTextColor(getResources().getColor(R.color.white));
			break;
		case 2:
			btn_all.setTextColor(getResources().getColor(R.color.white));
			btn_product.setTextColor(getResources().getColor(R.color.white));
			btn_voucher.setTextColor(getResources().getColor(R.color.black));
			break;

		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		// change color text tabs
		setColorTabs(0);
		btn_all.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.tab_menu1));

		btn_product.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.tab_menu1_selected));

		btn_voucher.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.tab_menu1_selected));

		root_view.removeAllViews();
		root_view.addView(layout_all);

	};
}
